var util = require("../util/util.js")
//跑得快
module.exports.createRoom = function(roomId,channelService,GameRemote) {
	console.log("new!!55555创建房间:"+roomId)
	var gameBasic = require("./basic/gameBasic.js")
	var logicBasic = require("./logic/hunanRunQuicklyLogic.js")
	var playerNum = 3
	var keyCard = {num : 3,type : 3} 							//关键牌，首次出牌要出关键牌
	var room = new gameBasic(roomId,"hunanRunQuickly",playerNum,channelService,GameRemote)
	room.roomMode = "hunanRunQuickly"
	room.luckys = [0,0,0]
	room.maxGameNumber = 1
	room.gameNumber = 0
	room.mustPlay = true 			//必出选项
	room.graded = false 			//梯度结算
	room.minCardValue = 130
	var logic = new logicBasic()
	var local = {}
	local.lastResult = false 		//最后出牌的牌型
	local.firstFlag = true 			//首次出牌标识
	local.curPlayer = -1 			//当前出牌玩家
	local.lastPlayer = -1 			//最后出牌玩家
	local.playFlag = false 			//出牌标识
	local.willPlayList = [] 		//未出牌时默认打出列表
	room.playTimer = 0 				//出牌定时器
	local.PLAY_TIME = 20000 		//出牌时间
	local.NOT_PLAY_TIME = 3000  	//没有牌出时的倒计时
	local.END_PLAY_TIME = 0 		//出牌倒计时时间
	local.initiative = true  		//主动性
	local.haveCard = false 			//被动出牌是否可打
	local.handRest = new Array(playerNum)
	local.scores = {} 				//分数列表
	local.councilScores = {} 		//本局分数列表
	local.playCounts = {} 			//参与次数
	local.winCounts = {} 			//胜利次数
	room.boms = {} 					//炸弹数量
	room.discardNumList = {}        //已出牌列表
	room.customData = false         //自定义数据
	//游戏开始
	room.gameBegin = function() {
		console.log("room.gameBegin")
		//重置本局分数
		local.councilScores = {}
		room.boms = {}
		room.discardNumList = {}
		local.lastResult = false
		local.lastPlayer = -1
		logic.sendCard(keyCard,room.luckys,room.minCardValue)
		local.curPlayer = logic.getCardVest(keyCard)
		for(var i = 0;i < room.players.length;i++){
			if(room.players[i].isActive){
				local.handRest[i] = 16
				if(room.players[i].isRobot){
					var notify = {
						cmd : "gameBegin",
						handCard : util.deepCopyArr(logic.playerHandler),
						curPlayer : local.curPlayer,
						chair : i
					}
					room.sendByUid(room.players[i].uid,notify)
				}else{
					var notify = {
						cmd : "gameBegin",
						handCard : logic.playerHandler[i],
						curPlayer : local.curPlayer,
						chair : i
					}
					room.sendByUid(room.players[i].uid,notify)
				}
			}
		}
		local.END_PLAY_TIME = (new Date()).getTime() + local.PLAY_TIME
		room.playTimer = setTimeout(local.notPlayCard,local.PLAY_TIME)
	}
	//出牌阶段
	local.nextPlay = function() {
		clearTimeout(room.playTimer)
		local.firstFlag = false
		local.curPlayer++
		for(var i = local.curPlayer;i < local.curPlayer + playerNum;i++){
			local.curPlayer = local.curPlayer % playerNum
			if(room.players[local.curPlayer].isActive){
				break
			}
		}
		//轮回最后出牌玩家时可重新出牌
		if(local.curPlayer == local.lastPlayer){
			local.lastResult = false
		}
		local.willPlayList = []
		//被动出牌检查
		if(local.lastResult){
			local.willPlayList = logic.getAllWinCardList(local.lastResult,logic.playerHandler[local.curPlayer])
			// console.log("local.willPlayList")
			// console.log(local.willPlayList)
		}
		var notify = {
			cmd : "nextPlay",
			curPlayer : local.curPlayer,
			haveCard : false,
			initiative : false
		}
		var time = local.PLAY_TIME
		if(local.lastResult){
			if(!local.willPlayList.length){
				time = local.NOT_PLAY_TIME
			}else{
				notify.haveCard = true
			}
		}else{
			notify.initiative = true
		}
		local.initiative = notify.initiative
		local.haveCard = notify.haveCard
		local.END_PLAY_TIME = (new Date()).getTime() + time
		room.playTimer = setTimeout(local.notPlayCard,time)
		room.sendAll(notify)
		local.playFlag = false
	}
	//出牌完成
	local.finishPlayCard = function(playList,cardList) {
		var chair = local.curPlayer
		local.playFlag = true
		for(var i = 0;i < playList.length;i++){
			logic.playerHandler[chair][playList[i]].state = false
			var tmpNum = logic.playerHandler[chair][playList[i]].num
			if(!room.discardNumList[tmpNum]){
				room.discardNumList[tmpNum] = 0
			}
			room.discardNumList[tmpNum]++
		}
		local.handRest[chair] -= playList.length
		if(playList && playList.length){
			local.lastPlayer = local.curPlayer
		}
		//发送通知
		var notify = {
			cmd : "playCard",
			lastResult : local.lastResult,
			result : cardList.length ? local.lastResult : false,
			chair : chair,
			isWin : local.handRest[chair] == 0
		}
		room.sendAll(notify)
		//炸弹加分
		if(cardList.length){
			if(local.lastResult.type == 10){
				for(var i = 0;i < playerNum;i++){
					if(i !== local.curPlayer && room.players[i].isReady){
						local.changeScore(i,-1)
						local.changeScore(local.curPlayer,1)
					}
				}
				if(!room.boms[local.curPlayer]){
					room.boms[local.curPlayer] = 0
				}
				room.boms[local.curPlayer]++
			}
		}
		local.checkWin()
	}
	//未出牌处理
	local.notPlayCard = function() {
		var chair = local.curPlayer
		var playList = []
		var cardList = []
		//首轮自动出关键牌
		// if(local.firstFlag == true){
		// 	for(var i = 0;i < logic.playerHandler[chair].length;i++){
		// 		if(logic.playerHandler[chair][i].num == keyCard.num && logic.playerHandler[chair][i].type == keyCard.type){
		// 			playList.push(i)
		// 			break
		// 		}
		// 	}
		// }
		if(local.lastResult == false){
			//主动出牌阶段出最小的牌  TODO 需考虑炸弹不可拆
			var minCard = false
			var minIndex = -1
			for(var i = 0;i < logic.playerHandler[chair].length;i++){
				if(logic.playerHandler[chair][i].state){
					if(minCard == false){
						minCard = logic.playerHandler[chair][i]
						minIndex = i
					}else{
						if(logic.compareType(minCard,logic.playerHandler[chair][i])){
							minCard = logic.playerHandler[chair][i]
							minIndex = i
						}
					}
				}
			}
			// console.log("minIndex : "+minIndex)
			// console.log(logic.playerHandler[chair][minIndex])
			playList.push(minIndex)
		}else if(room.mustPlay){
			if(local.willPlayList.length){
				for(var i in local.willPlayList[0]){
					playList.push(local.willPlayList[0][i].index)
				}
			}
		}
		if(playList && playList.length){
			for(var i = 0;i < playList.length;i++){
				cardList.push(logic.playerHandler[chair][playList[i]])
			}
			local.lastResult = logic.getCardType(cardList,local.handRest[chair])
		}
		local.finishPlayCard(playList,cardList)
	}
	//胜利检查
	local.checkWin = function() {
		var chair = local.curPlayer
		//test1
		// if(room.players[chair].uid > 10000){
		// 	local.settlement()
		// 	return
		// }
		//判断打完
		if(local.handRest[chair] == 0){
			//游戏结束
			local.settlement()
		}else{
			//下一个人出牌
			local.nextPlay()
		}
	}
	//结算
	local.settlement = function() {
		clearTimeout(room.playTimer)
		var allScore = 0
		for(var i = 0;i < playerNum;i++){
			if(i !== local.curPlayer && room.players[i].isReady){
				var tmpScore = local.handRest[i]
				if(room.graded){
					//梯度结算
					if(tmpScore === 16){
						tmpScore *= 4
					}else if(tmpScore > 10 && tmpScore <= 15){
						tmpScore *= 3
					}else if(tmpScore > 5 && tmpScore <= 10){
						tmpScore *= 2
					}
				}else{
					//春天加倍
					if(tmpScore === 16){
						tmpScore *= 2
					}
				}
				allScore += tmpScore
				local.changeScore(i,-tmpScore)
			}else{
				if(!local.winCounts[i]){
					local.winCounts[i] = 0
				}
				local.winCounts[i]++
			}
			if(!local.playCounts[i]){
				local.playCounts[i] = 0
			}
			local.playCounts[i]++
		}
		local.changeScore(local.curPlayer,allScore)
		var notify = {
			cmd : "settlement",
			win : local.curPlayer,
			scores : local.scores,
			councils : local.councilScores,
			playerHandler : logic.playerHandler,
			bombs : room.boms
		}
		room.sendAll(notify)
		room.gameSettlement()
		room.gameNumber++
		if(room.gameNumber >= room.maxGameNumber){
			room.gameOverBefore(local.curPlayer,local.scores)
		}
	}
	//游戏结束
	room.gameOverBefore = function() {
		clearTimeout(room.playTimer)
		room.gameOver()
	}
	//分数改变
	local.changeScore = function(chair,score) {
		if(!local.scores[chair]){
			local.scores[chair] = 0
		}
		local.scores[chair] += score
		if(!local.councilScores[chair]){
			local.councilScores[chair] = 0
		}
		local.councilScores[chair] += score
		var notify = {
			cmd : "changeScore",
			chair : chair,
			changeScore : score,
			score : local.scores[chair],
			council : local.councilScores[chair]
		}
		room.sendAll(notify)
	}
	//获取当前房间信息
	room.handle.getRoomInfo = function(uid,sid,param,cb) {
		var chair = room.chairMap[uid]
		var info = {
			roomType : room.roomType,
			roomMode : room.roomMode,
			roomId : room.roomId,
			keyCard : keyCard,
			state : room.beginFlag,
			PLAY_TIME : local.PLAY_TIME,
			NOT_PLAY_TIME : local.NOT_PLAY_TIME,
			END_PLAY_TIME : local.END_PLAY_TIME,
			players : room.getPlayersInfo(),
			countDownEndTime : room.countDownEndTime,
			curTime : (new Date()).getTime(),
			curPlayer : local.curPlayer,
			lastResult : local.lastResult,
			firstFlag : local.firstFlag,
			lastPlayer : local.lastPlayer,
			handCard : logic.playerHandler[chair],
			chair : chair,
			handRest : local.handRest,
			initiative : local.initiative,
			haveCard : local.haveCard,
			scores : local.scores,
			councils : local.councilScores,
			maxGameNumber : room.maxGameNumber,
			gameNumber : room.gameNumber,
			maxScore : room.maxScore,
			minScore : room.minScore,
			rate : room.rate,
			charge : room.charge,
			willWin : room.willWin,
			mustPlay : room.mustPlay,
			graded : room.graded,
			matchType : room.matchType,
			discardNumList : room.discardNumList,
			customData : room.customData
		}
		cb(true,info)
	}
	room.getRoomData = function() {
		var info = {
			roomType : room.roomType,
			roomMode : room.roomMode,
			roomId : room.roomId,
			keyCard : keyCard,
			scores : local.scores,
			maxGameNumber : room.maxGameNumber,
			gameNumber : room.gameNumber,
			mustPlay : room.mustPlay,
			graded : room.graded,
			players : {},
			playCounts : local.playCounts,
			winCounts : local.winCounts
		}
	    for(var i in room.players){
	     	if(room.players[i].isActive){
	     		info.players[i] = room.players[i].getEasyInfo()
	     	}
	    }
	    return info
	}
	//要不起,放弃出牌
	room.handle.giveUp = function(uid,sid,param,cb) {
		var chair = room.chairMap[uid]
		if(chair !== local.curPlayer){
			// console.log("chair : "+chair)
			// console.log("curPlayer : "+local.curPlayer)
			cb(false,"还没到你的轮次")
			return
		}
		if(!local.lastResult){
			cb(false,"必须出牌")
			return
		}
		if(room.mustPlay && local.willPlayList.length){
			cb(false,"有大必须出")
			return
		}
		//首次出牌要包含关键牌
		// if(local.firstFlag == true){
		// 	cb(false,"必须包含关键牌")
		// 	return
		// }
		local.finishPlayCard([],[])
		cb(true)
	}
	//出牌
	room.handle.playCard = function(uid,sid,param,cb) {
		var chair = room.chairMap[uid]
		if(chair !== local.curPlayer){
			// console.log("chair : "+chair)
			// console.log("curPlayer : "+local.curPlayer)
			cb(false,"还没到你的轮次")
			return
		}
		var playList = param.playList
		if(!playList || !playList.length){
			cb(false,"出牌参数错误")
			return
		}
		var cardList = []
		for(var i = 0;i < playList.length;i++){
			if(!logic.playerHandler[chair][playList[i]].state){
				cb(false)
				return
			}
			cardList.push(logic.playerHandler[chair][playList[i]])
		}
		// console.log("cardList :")
		// console.log(cardList)
		//首次出牌要包含关键牌
		// if(local.firstFlag == true){
		// 	var flag = false
		// 	for(var i = 0;i < cardList.length;i++){
		// 		if(cardList[i].num == keyCard.num && cardList[i].type ==keyCard.type){
		// 			flag = true
		// 			break
		// 		}
		// 	}
		// 	if(!flag){
		// 		cb(false,"必须包含关键牌")
		// 		return
		// 	}
		// }
		//获取牌型
		var result = logic.getCardType(cardList,local.handRest[chair])
		// console.log(result)
		if(!result.type){
			cb(false,"不支持的牌型")
			return
		}
		if(local.lastResult){
			//牌型必须一样且大于上一个出牌
			if(logic.compare(local.lastResult,result)){
				local.lastResult = result
				local.finishPlayCard(playList,cardList)
				cb(true)
			}else{
				cb(false,"必须大于上一个牌型")
			}
		}else{
			local.lastResult = result
			local.finishPlayCard(playList,cardList)
			cb(true)
		}
	}
	room.setKeyCard = function(card) {
		keyCard = card
	}
	room.getLocal = function() {
		return local
	}
	room.getLogic = function() {
		return logic
	}
	return room
}